import { IDEFormMDCtrl } from '@ibiz/model-core';
import { FormMDCtrlController } from './form-mdctrl.controller';

/**
 * 表单多数据部件项控制器
 *
 * @author chitanda
 * @date 2022-08-03 11:08:20
 * @export
 * @class MDCtrlFormController
 * @extends {FormController<MDCtrlFormModel>}
 */
export class FormMDCtrlContentTypeController {
  get data(): IData[] {
    return this.parent.state.contentCtrlData as IData[];
  }

  /**
   * 表单多数据部件模型
   *
   * @author zk
   * @date 2023-07-29 05:07:33
   * @type {IDEFormMDCtrl}
   * @memberof FormMDCtrlContentTypeController
   */
  model!: IDEFormMDCtrl;

  /**
   * Creates an instance of FormMDCtrlControlController.
   * @author zk
   * @date 2023-07-28 09:07:22
   * @param {FormMDCtrlController} c
   * @memberof FormMDCtrlControlController
   */
  constructor(public parent: FormMDCtrlController) {
    this.model = this.parent.model;
  }

  /**
   * 初始化
   *
   * @author zk
   * @date 2023-07-25 10:07:11
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof FormMDCtrlController
   */
  async onInit(): Promise<void> {}

  /**
   * 内部表单数据发生改变，同步contentCtrlData并设置外部表单值
   *
   * @author zk
   * @date 2023-07-30 05:07:18
   * @param {IData[]} data
   * @memberof FormMDCtrlController
   */
  onDataChange(data: IData[]): void {
    this.parent.state.contentCtrlData = data;
    this.parent.setFormDataValue();
  }

  /**
   * 内部表单项数据发生改变，同步contentCtrlData并设置外部表单值
   *
   * @author zk
   * @date 2023-07-30 05:07:11
   * @param {IData} data
   * @param {number} index
   * @memberof FormMDCtrlController
   */
  onDataItemChange(data: IData, index: number): void {
    (this.parent.state.contentCtrlData as IData[])[index] = data;
    this.parent.setFormDataValue();
  }

  /**
   * 数据删除
   *
   * @author zk
   * @date 2023-07-30 05:07:32
   * @param {number} index
   * @memberof FormMDCtrlController
   */
  onDataRemove(index: number): void {
    if (index < 0) {
      return;
    }
    this.parent.state.contentCtrlData.splice(index, 1);
    this.parent.setFormDataValue();
  }

  /**
   * 数据插入
   *
   * @author zk
   * @date 2023-07-31 12:07:27
   * @param {IData} [data]
   * @memberof FormMDCtrlContentTypeController
   */
  onDataInsert(data?: IData): void {
    this.parent.state.contentCtrlData.push(data || {});
    this.parent.setFormDataValue();
  }

  /**
   * 初始化数据
   *
   * @author zk
   * @date 2023-07-30 08:07:32
   * @memberof FormMDCtrlContentTypeController
   */
  async initData(): Promise<void> {
    const name =
      this.model.appDEFieldId || this.model.fieldName || this.model.id;
    if (name) {
      if (
        this.model.contentType === 'REPEATER' &&
        this.model.detailStyle === 'STYLE3'
      ) {
        this.parent.state.contentCtrlData = this.parent.data[name] || {};
      } else {
        this.parent.state.contentCtrlData = this.parent.data[name] || [];
      }
    }
  }
}
